/**
 * Created by zy on 2016/6/22.
 * 缺陷维修建议 - 管体缺陷
 */


;(function ($, window, document, undefined) {

    // 管道
    var $pipeline = $('#JQ_pipeline').select3();
    // 管段
    var $segment = $('#JQ_segment').select3({
        title: '管段'
    });
    // 起点位置
    var $begin = $('#JQ_begin').select3({
        title: '起点位置',
        server: true,
        mileType: 'float',
        param: {
            'pipeLineId': $pipeline,
            'pipeSegmentId': $segment
        }
    });
    // 终点位置
    var $end = $('#JQ_end').select3({
        title: '终点位置',
        server: true,
        mileType: 'float',
        param: {
            'pipeLineId': $pipeline,
            'pipeSegmentId': $segment,
            'beginSignId': $begin
        }
    });
    // 检测任务
    var $task = $('#JQ_task').select3({search: false});
    // 建议维修方法数据
    var repairData = function () {
        var temp = $('#JQ_repair_data').html();
        if (temp) {
            temp = temp.substr(0, temp.lastIndexOf(','));
            temp = '[' + temp + ']';
            temp = eval('(' + temp + ')');
        }
        return temp;
    }();
    // 建议维修方法
    var $repair = $('#JQ_repair').select3({
        search: false,
        data: repairData
    });
    // 检测时间
    var $date_01 = $('#JQ_input_date_01');
    // 最迟维修时间 - 1
    var $date_02 = $('#JQ_input_date_02');
    // 最迟维修时间 - 2
    var $date_03 = $('#JQ_input_date_03');
    // 维修建议表格
    var $table_advise = $('#JQ_table_advise').checkbox3();
    // 下载表单
    var $download_form = $('#JQ_download_form');
    // 生成表单
    var $build_form = $('#JQ_build_form');

    // 填充管段
    function fillSegment(id) {
        if (id) {
            DyyBase.ajax(DyyBase.url_segment(), {pipeLineId: id}, function (dataset) {
                var json = DyyBase.getSelect(dataset);
                $segment.add(json);
            });
        } else {
            $segment.add([]);
        }
    }

    // 填充起点 & 终点
    function fillPos(id, tag, callback) {
        if (id) {
            if (tag === 'line') {
                DyyBase.ajax(DyyBase.url_pipe_pos(), {pipeLineId: id}, function (dataset) {
                    var begin = DyyBase.getPos(dataset, 'begin', true);
                    var end = DyyBase.getPos(dataset, 'end', true);
                    $begin.asset(begin);
                    $end.asset(end);
                }, {async: false});
            } else if (tag === 'segment') {
                DyyBase.ajax(DyyBase.url_segment_pos(), {pipeSegmentId: id}, function (dataset) {
                    var begin = DyyBase.getPos(dataset, 'begin', true);
                    var end = DyyBase.getPos(dataset, 'end', true);
                    $begin.asset(begin);
                    $end.asset(end);
                }, {async: false});
            }
        } else {
            $begin.add([]);
            $end.add([]);
        }

        callback();
    }

    // 填充检测任务
    function fillTask() {
        var pid = $pipeline.val();
        var bv = $begin.val('mile');
        var ev = $end.val('mile');
        if (pid && DyyBase.notEmpty(bv) && DyyBase.notEmpty(ev)) {
            DyyBase.ajax(defectApi.url_advise_task(), {
                pipeLineId: pid,
                beginMile: bv,
                endMile: ev
            }, function (dataset) {
                if(dataset.bool){
                    var arr = [];
                    for(var i = 0, len = dataset.result.length; i < len; i++){
                        arr.push({
                            id:dataset.result[i]['id'],
                            text:dataset.result[i]['name'],
                            mile:dataset.result[i]['checkTime']
                        });
                    }
                    if(arr.length){
                        $task.asset(arr);
                        $date_01.val(arr[0]['mile']);
                    }else{
                        $task.add([]);
                        $date_01.val('');
                    }
                }
            });
        } else {
            $task.add([]);
        }
    }

    // 触发管道
    $pipeline.element.on('select', function (e, v) {
        var id = v || $pipeline.val();
        fillSegment(id);
        fillPos(id, 'line', fillTask);
    });
    // 触发管段
    $segment.element.on('select', function (e, v) {
        var id = v || $segment.val();
        fillPos(id, 'segment', fillTask);
    });
    // 触发检测任务
    $task.element.on('select', function(e, v){
        var time = $task.val('mile');
        $date_01.val(time);
    });
    // 触发检测时间
    $date_01.on('blur', function(){
        var $this = $(this);
        var v = $this.val();
        if(v){
            var pid = $pipeline.val();
            var bv = $begin.val('mile');
            var ev = $end.val('mile');
            DyyBase.ajax(defectApi.url_advise_task(), {
                pipeLineId: pid,
                beginMile: bv,
                endMile: ev,
                checkTime: v
            }, function(dataset){
                if(dataset.bool){
                    var arr = [];
                    for(var i = 0, len = dataset.result.length; i < len; i++){
                        arr.push({
                            id:dataset.result[i]['id'],
                            text:dataset.result[i]['name'],
                            mile:dataset.result[i]['checkTime']
                        });
                    }
                    if(arr.length){
                        $task.asset(arr);
                        $date_01.val(arr[0]['mile']);
                    }else{
                        $task.add([]);
                    }
                }
            });
        }
    });


    // 查询对象
    var filter = {
        // 获得查询条件
        getSearch: function () {
            var data = {};
            if (!DyyBase.search) {
                data.pipeId = '-1';
                return data;
            }
            data.mode = true;
            data.pipeId = function () {
                var v = $pipeline.val();
                if (v) {
                    return v;
                } else {
                    $pipeline.element.TIP({content: '管道名称不能为空!'});
                    data.mode = false;
                }
                return '';
            }();
            data.pipeLineName = function () {
                var v = $pipeline.val('text');
                if (v) {
                    return v;
                }
                return '';
            }();
            data.instTaskId = function () {
                var v = $task.val();
                if (v) {
                    return v;
                } else {
                    $task.element.TIP({content: '检测任务不能为空!'});
                    data.mode = false;
                }
                return '';
            }();
            data.beginId = function () {
                var v = $begin.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.beginMileage = function () {
                var v = $begin.val('mile');
                if (DyyBase.notEmpty(v)) {
                    return v;
                } else {
                    $begin.element.TIP({content: '起点位置不能为空!'});
                    data.mode = false;
                }
                return '';
            }();
            data.beginName = function () {
                var v = $begin.val('text');
                if (v) {
                    return v;
                }
                return '';
            }();
            data.endId = function () {
                var v = $end.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.endMileage = function () {
                var v = $end.val('mile');
                if (DyyBase.notEmpty(v)) {
                    return v;
                } else {
                    $end.element.TIP({content: '起点位置不能为空!'});
                    data.mode = false;
                }
                return '';
            }();
            data.endName = function () {
                var v = $end.val('text');
                if (v) {
                    return v;
                }
                return '';
            }();
            data.taskName = function () {
                var v = $task.val('text');
                if (v) {
                    return v;
                }
                return '';
            }();
            data.planRepairType = function () {
                var v = $repair.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.planRepairName = function () {
                var v = $repair.val('text');
                if (v) {
                    return v;
                }
                return '';
            }();
            data.checkTime = function () {
                var v = $date_01.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.latestBeginTime = function () {
                var v = $date_02.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            data.latestEndTime = function () {
                var v1 = $date_02.val();
                var v2 = $date_03.val();
                if (v2) {
                    if (v1 && !(Dyy.checkDateLate(v1, v2))) {
                        $date_03.TIP({content: '结束日期应当晚于开始日期!'});
                        data.mode = false;
                    }
                    return v2;
                }
                return '';
            }();
            return data;
        },
        // 获得导出条件
        getExport: function () {
            return filter.getSearch();
        },
        // 获得选中建议
        getSelected: function () {
            var $chks = $table_advise.find('i.zy-checkbox');
            var param = [];
            $chks.each(function () {
                var $this = $(this);
                if ($this.hasClass('active')) {
                    param.push($this.attr('data-id'));
                }
            });
            return param;
        },
        // 下载评价报告
        getDownLoad: function () {
            var data = {};
            data.mode = true;
            data.taskId = function(){
                var v = $task.val();
                if(v){
                    return v;
                }else{
                    $task.element.TIP({content: '检测任务不能为空!'});
                    data.mode = false;
                }
                return '';
            }();
            data.taskName = function(){
                var v = $task.val('text');
                if(v){
                    return v;
                }else{
                    $task.element.TIP({content: '检测任务不能为空!'});
                    data.mode = false;
                }
                return '';
            }();
            data.pipeLineName = function(){
                var v = $pipeline.val('text');
                if(v){
                    return v;
                }else{
                    $pipeline.element.TIP({content: '管道名称不能为空!'});
                    data.mode = false;
                }
                return '';
            }();
            return data;
        }
    };

    // 加载维修建议表格
    var DTADV = $table_advise.DataTable({
        'language': {
            'zeroRecords': DyyBase.defect_empty()
        },
        'info': false,
        'autoWidth': false,
        'serverSide': true,
        'pageLength': 1000,
        'ordering': false,
        'processing': false,
        'searching': false,
        'lengthChange': false,
        'paging': false,
        'ajax': function (data, callback) {
            var param = filter.getSearch();
            DyyBase.ajax(defectApi.url_advise_list(), param, function (dataset) {
                var returnData = {};
                returnData.draw = data.draw;
                returnData.recordsTotal = 1000;
                returnData.recordsFiltered = 1000;
                returnData.data = DyyBase.clearNull(dataset.result);
                callback(returnData);
            });
        },
        'drawCallback': function () {
            $('i.zy-checkbox-all').trigger('clear');
        },
        'columns': [
            {
                data: 'defectId', render: function (data) {
                return '<i class="zy-checkbox" data-id="' + data + '" title="选中"></i>';
            }
            },
            {
                data: 'featureSubType', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'mileage', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'clock', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'erf', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'repairSuggestion', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'planRepairTime', render: function (data) {
                return '<span title="' + Dyy.getDate(data) + '">' + Dyy.getDate(data) + '</span>';
            }
            },
            {
                data: 'planRepairType', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'evaluateTime', render: function (data) {
                return '<span title="' + Dyy.getDate(data) + '">' + Dyy.getDate(data) + '</span>';
            }
            },
            {
                data: 'assessDepartment', render: function (data) {
                return '<span title="' + data + '">' + data + '</span>';
            }
            },
            {
                data: 'defectId', render: function (data) {
                return '<i data-id="' + data + '" class="zy-details-icon" title="展开详情"></i>';
            }
            }
        ]
    });

    // 重绘表格
    function draw() {
        if (DTADV) {
            DTADV.draw();
        }
    }

    // 搜索
    $('#JQ_search_advise').click(function () {
        DyyBase.search = true;
        var param = filter.getSearch();
        if (param.mode) {
            draw();
            filter.getExport = param;
        }
    });

    // 详情模板
    var adviseTemplate = [
        {name: 'customNumber', title: '缺陷编号：'},
        {name: 'featureSubType', title: '缺陷类型：'},
        {name: 'mileage', title: '绝对距离(m)：'},
        {name: 'erf', title: 'ERF：'},
        {
            name: 'length', title: '长/宽/深(mm)：', render: function (d, r) {
            return r.length + '/' + r.width + '/' + r.depth;
        }
        },
        {name: 'clock', title: '时钟位置(h:min)：'},
        {name: 'repairSuggestion', title: '维修建议：'},
        {
            name: 'planRepairTime', title: '最迟维修时间：', render: function (d) {
            return Dyy.getDate(d);
        }
        },
        {name: 'planRepairType', title: '建议维修方法：'},
        {
            name: 'evaluateTime', title: '评价时间：', render: function (d) {
            return Dyy.getDate(d);
        }
        },
        {name: 'assessDepartment', title: '评价单位：'}
    ];

    // 展开详情
    $table_advise.on('click', 'i.zy-details-icon', function () {
        DyyBase.showDetails($(this), DTADV, $table_advise, adviseTemplate);
    });

    // 导出
    $('#JQ_export_btn').click(function () {
        DyyBase.search = true;
        var param = filter.getExport;
        if (param instanceof Function) {
            param = param();
        }
        if(param.mode){
            //param.fileName = param.pipeLineName + param.taskName + '缺陷维修建议';
            $(this).EXPT({
                name: param.pipeLineName + param.taskName + '缺陷维修建议',
                param: param,
                server: DyyBase.root_path + '/pbf/suggestion/exportExcel.json'
            });
        }
    });

    // 下载评价报告
    $('#JQ_download_btn').click(function () {
        var param = filter.getDownLoad();
        if(param.mode){
            $download_form.empty();
            for(var k in param){
                var $input = $('<input type="hidden">');
                $input.prop('name', k).val(param[k]);
                $download_form.append($input);
            }
            $download_form.submit();
        }
    });

    // 生成维修项目
    $('#JQ_build_btn').click(function () {
        DyyBase.search = true;
        var $this = $(this);
        var ids = filter.getSelected();
        if (ids.length > 0) {
            $build_form.empty();
            var param = filter.getSearch();
            for (var i = 0, len = ids.length; i < len; i++) {
                var $input = $('<input type="hidden" name="defectId">');
                $input.val(ids[i]);
                $build_form.append($input);
            }
            for (var o in param) {
                var $hidden = $('<input type="hidden">');
                $hidden.prop('name', o).val(param[o]);
                $build_form.append($hidden);
            }
            $build_form.submit();
        } else {
            $this.MSG({
                content: '请选择需要生成项目的维修建议!'
            });
        }
    });

})(jQuery, window, document);

// 下载回调json
window.downloadResult = function (data) {
    if (!data.bool) {
        $(this).MSG({
            content: '没有需要下载的文件',
            type: 'error'
        });
    }
};